package com.hch.service;

import com.hch.NotFoundException;
import com.hch.dao.BlogRepository;
import com.hch.domain.Blog;
import com.hch.utils.MarkdownUtils;
import com.hch.utils.MyBeanUtils;
import com.hch.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.lang.reflect.Type;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    //注入blogRepository
    @Autowired
    private BlogRepository blogRepository;


    @Transactional
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.findById(id).get();
    }

    @Transactional  //会覆盖BlogRepository中的事务
    @Override
    public Blog getAndCovertBlog(Long id) {
        Blog blog = blogRepository.findById(id).get();
        if (blog == null) {
            throw new NotFoundException("博客不存在");
        }   //为了防止将转化后的html格式保存到数据库中，操作如下
        Blog b = new Blog();
        BeanUtils.copyProperties(blog, b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        //根据blog id更新浏览次数
        blogRepository.updateViews(id);
        return b;
    }

    //new Specification<Blog>()处理查询条件 criteriaQuery查询的条件的储存容器 criteriaBuilder 模糊查询 like / = ...
    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                //判断博客的标题是否为空，并且将组合查询条件的title保存到predicates
                if (!"".equals(blogQuery.getTitle()) && blogQuery.getTitle() != null) {
                    predicates.add(criteriaBuilder.like(root.<String>get("title"), "%" + blogQuery.getTitle()));
                }
                //判断博客分类是否为空，不为空则将条件保存在predicates
                if (blogQuery.getTypeId() != null) {
                    predicates.add(criteriaBuilder.equal(root.<Type>get("type").get("id"), blogQuery.getTypeId()));
                }
                if (blogQuery.isRecommend()) {
                    predicates.add(criteriaBuilder.equal(root.<Boolean>get("recommend"), blogQuery.isRecommend()));
                }
                //将查询条件的列表转化为数组，并且要声明列表的size
                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId() == null) {
            //如果id为空说明是新增的博客
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        } else {
            //不为空则是更新博客
            blog.setUpdateTime(new Date());
        }
        return blogRepository.save(blog);
    }


    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }


    @Override
    public Page<Blog> listBlogByTagId(Long tagId, Pageable pageable) {
        //去查询JPA的CriteriaQuery API使用方法
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //关联表的查询,对应Blog实体类中的 tags 多对多
                Join join = root.join("tags");
                //如果id == 传递过来的tagId，则会关联数据库，返回pageable
                return criteriaBuilder.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public Page<Blog> listSearchBlog(String query, Pageable pageable) {
        return blogRepository.findByQuery(query, pageable);
    }

    @Transactional
    @Override
    public List<Blog> listRecommendTopBlog(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRepository.findTopBlog(pageable);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.findById(id).get();
        if (b == null) {
            throw new NotFoundException("该博客不存在");
        }
        //将blog赋值给修改的对象,老师写反了，注意...
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRepository.deleteById(id);
    }


    @Override
    public Map<String, List<Blog>> archiveBlog() {
        //返回博客的年份，参考sql语句 SELECT DATE_FORMAT(b.update_time,"%Y") as year from t_blog b GROUP BY year ORDER BY year DESC;
        List<String> years = blogRepository.findGroupYears();
        //Map<String,List<Blog>> map = new HashMap<>();
        //使用LinkedHashMap不会出现年份错乱的情况
        Map<String,List<Blog>> map = new LinkedHashMap<>();
        //将每个年份对应的博客信息构造的集合存入map中
        for (String year : years) {
            map.put(year,blogRepository.findByYear(year));
            //测试年份输出是否正常
            //System.out.println(year);
            //System.out.println(blogRepository.findByYear(year).toString());
        }
        return map;
    }

    @Override
    public Long blogCount() {
        //查询的是blog表中的数据条数
        return blogRepository.count();
    }
}
